package com.mazaiting.sms.service.impl;

import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.exceptions.EmptyObjectException;
import com.mazaiting.common.core.utils.StringUtil;
import com.mazaiting.redis.service.IRedisService;
import com.mazaiting.sms.config.SmsProperties;
import com.mazaiting.sms.domain.dto.SmsDto;
import com.mazaiting.sms.domain.entity.MsgSmsSend;
import com.mazaiting.sms.domain.entity.MsgSmsTemplate;
import com.mazaiting.sms.service.IMsgSmsSendService;
import com.mazaiting.sms.service.IMsgSmsTemplateService;
import com.mazaiting.sms.service.ISmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/***
 * 本地短信服务发送短信验证码
 * @author mazaiting
 * @create_time 2022/4/12 16:14
 */
@Slf4j
@Service
@Qualifier("localSmsServiceImpl")
@RequiredArgsConstructor
public class LocalSmsServiceImpl implements ISmsService {

//    @Override
//    public void send(String phone, String templateCode, Map<String, Object> param) {
//        log.info("本地短信发送: {}, 模板编号: {}, 参数: {}", phone, templateCode, param);
//    }
    private final IMsgSmsTemplateService msgSmsTemplateService;

    private final IMsgSmsSendService msgSmsSendService;

    private final IRedisService redisService;

    private final SmsProperties smsProperties;

    @Override
    public boolean send(SmsDto smsDto) throws EmptyObjectException {
        // 根据码值获取短信模板
        Optional<MsgSmsTemplate> msgSmsTemplateOpt = msgSmsTemplateService.findByCode(smsDto.getCode());
        if (msgSmsTemplateOpt.isEmpty()) {
            throw new EmptyObjectException(ResultCode.MSG_SMS_TEMPLATE_EMPTY);
        }
        // 手机号
        String phone = smsDto.getPhone();
        // 验证码
        String code = StringUtil.getRandomString(smsProperties.getDigits());
        MsgSmsTemplate msgSmsTemplate = msgSmsTemplateOpt.get();
        // 短信模板
        String content = msgSmsTemplate.getContent();
        Map<String, String> map = new HashMap<>();
        map.put("${sign_name}", msgSmsTemplate.getSignName());
        map.put("${code}", code);
        content = StringUtil.replaceField(content, map);

        MsgSmsSend msgSmsSend = new MsgSmsSend();
        msgSmsSend.setSmsId(msgSmsTemplate.getId());
        msgSmsSend.setChannel(smsDto.getPlatform());
        msgSmsSend.setPhone(smsDto.getPhone());
        msgSmsSend.setStatus(true);
        msgSmsSend.setContent(content);
        msgSmsSendService.save(msgSmsSend);

        // 存入 redis
        redisService.set(SecurityConst.SMS_CODE_PREFIX + phone, code, smsProperties.getExpiration(), TimeUnit.SECONDS);
        log.info("短信发送成功: 手机号 - " + phone + ", 验证码: " + code);
        return true;
    }
}
